import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import config from '@/config'
import { useUserStore } from '@/stores'

// 是否显示重新登录
export let isRelogin = { show: false }

// 创建请求配置
const service = {
  baseURL: config.baseUrl,
  timeout: 10000,
  header: {
    'Content-Language': 'zh_CN'
  }
}

// 处理请求参数
function tansParams(params: any): string {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    if (value !== null && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          const params = propName + '[' + key + ']'
          const subPart = encodeURIComponent(params) + "="
          result += subPart + encodeURIComponent(value[key]) + "&"
        }
      } else {
        result += encodeURIComponent(propName) + "=" + encodeURIComponent(value) + "&"
      }
    }
  }
  return result.slice(0, -1)
}

// 请求拦截器
function requestInterceptor(config: any) {
  // 是否需要设置 token
  const isToken = (config.header || {}).isToken === false
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.header || {}).repeatSubmit === false

  // 设置请求头
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }

  // 如果是 POST/PUT 请求，添加 Content-Type
  if (config.method?.toUpperCase() === 'POST' || config.method?.toUpperCase() === 'PUT') {
    config.header['Content-Type'] = 'application/json;charset=utf-8'
  }

  // get请求映射params参数
  if (config.method?.toLowerCase() === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params)
    config.params = {}
    config.url = url
  }

  return config
}

// 响应拦截器
function responseInterceptor(response: any) {
  const code = response.data.code || 200
  const msg = errorCode[code as keyof typeof errorCode] || response.data.msg || errorCode['default']

  if (code === 401) {
    if (!isRelogin.show) {
      isRelogin.show = true
      uni.showModal({
        title: '系统提示',
        content: '登录状态已过期，是否重新登录？',
        success: (res) => {
          isRelogin.show = false
          if (res.confirm) {
            useUserStore().LogOut().then(() => {
              uni.reLaunch({ url: '/pages/login' })
            })
          }
        }
      })
    }
    return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
  } else if (code === 500) {
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
    return Promise.reject(new Error(msg))
  } else if (code === 601) {
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
    return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
    return Promise.reject('error')
  }
  return Promise.resolve(response.data)
}

// 错误处理
function errorHandler(error: any) {
  let { message } = error
  if (message === "Network Error") {
    message = "后端接口连接异常"
  } else if (message.includes("timeout")) {
    message = "系统接口请求超时"
  } else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常"
  }
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
  return Promise.reject(error)
}

// 请求方法
const request = (config: any) => {
  // 合并默认配置
  const finalConfig = {
    ...service,
    ...config,
    header: {
      ...service.header,
      ...config.header
    }
  }

  // 请求拦截
  const interceptedConfig = requestInterceptor(finalConfig)

  return new Promise((resolve, reject) => {
    uni.request({
      ...interceptedConfig,
      url: service.baseURL + interceptedConfig.url,
      success: (res: any) => {
        responseInterceptor(res)
          .then(resolve)
          .catch(reject)
      },
      fail: (err: any) => {
        errorHandler(err)
          .catch(reject)
      }
    })
  })
}

// 文件下载方法
export function download(url: string, params: any, filename: string) {
  uni.showLoading({ title: '正在下载数据，请稍候' })

  const fullUrl = service.baseURL + url
  const queryString = params ? '?' + tansParams(params) : ''

  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: fullUrl + queryString,
      header: {
        'Authorization': 'Bearer ' + getToken()
      },
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (result) => {
              resolve(result.savedFilePath)
            },
            fail: (err) => {
              reject(err)
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        } else {
          reject(new Error('下载失败'))
          uni.hideLoading()
        }
      },
      fail: (err) => {
        reject(err)
        uni.hideLoading()
      }
    })
  })
}

export default request
